package com.hnkywl.sts.service.kcgl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.hnkywl.sts.dao.cggl.CgdDao;
import com.hnkywl.sts.dao.xsgl.GdDao;
import com.hnkywl.sts.dao.xsgl.KhDao;
import com.hnkywl.sts.entity.cggl.Cgd;
import com.hnkywl.sts.entity.xsgl.Gd;
import com.hnkywl.sts.entity.xsgl.Kh;
import com.hnkywl.sts.service.base.WebserviceTransService;
import net.ruixin.orm.hibernate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 撤单
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-5-9
 * Time: 下午9:07
 * To change this template use File | Settings | File Templates.
 */
@Service
public class CxgdService {
    private GdDao gdDao;
    private KhDao khDao;
    private CgdDao cgdDao;
    private WebserviceTransService webserviceTransService;
    private final static int COUNT_OUT = 20;
    private final static int TIME_OUT = 10000;

    /**
     * 查询所有撤单
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Transactional
    public String findAllCancelGdList(String khbm, String ckmc, String code, String ggxh, String wzmc, int pageNo, int pageSize) {
        Page<Gd> gdPage = this.gdDao.findCancellationList(khbm, ckmc, code, ggxh, wzmc, pageNo, pageSize);
        List<Gd> gdList = gdPage.getResult() == null ? new ArrayList<Gd>() : gdPage.getResult();
        return "{\"total\":" + gdPage.getTotalCount() + ",\"rows\":" + new GsonBuilder().setDateFormat("yyyy-MM-dd").create().toJson(gdList) + "}";
    }


    @Transactional
    public synchronized List<Map<String, Object>> cd(String gdIds) throws Exception {
        String[] gdStr = gdIds.split(",");
        List<Gd> gdList = new ArrayList<Gd>();
        for (int i = 0; i < gdStr.length; i++) {
            gdList.add(gdDao.get(Long.parseLong(gdStr[i])));
        }

        if (gdList != null) {
            List<Map<String, Object>> map = new ArrayList<Map<String, Object>>();
            String json = this.createCdJsonToInterFace(gdList);
          //  String result = webserviceTransService.transCdWebServiceArgs(/*gdList.get(0).getKh().getCggs().getBm()*/null, json);
            String result = null;
            Gson gson = new Gson();
            try {
                map = gson.fromJson(result, new TypeToken<List<Map<String, Object>>>() {
                }.getType());
            } catch (Exception e) {
                Map<String, Object> value = gson.fromJson(result, new TypeToken<Map<String, Object>>() {
                }.getType());
                map.add(value);
            }
            return map;
        }
        return null;
    }


    public StringBuffer tipResponse(Map<String, Object> map, String message) {
        StringBuffer Failures = new StringBuffer();
        Failures.append("挂牌号为").append(map.get("hangcode") == null ? "空" : map.get("hangcode").toString()).append("；");
        Failures.append(message).append("；");
        Failures.append("撤牌成功量：").append(map.get("surplus") == null ? 0 : map.get("surplus").toString()).append("；");
        Failures.append("已销售量：").append(map.get("handled") == null ? 0 : map.get("handled").toString()).append("；");
        return Failures;
    }

    public void checkJsonResponse(List<Map<String, Object>> maps) throws RuntimeException {
        for (int i = 0; i < maps.size(); i++) {
            if (maps.get(i).get("code") == null)
                throw new RuntimeException("第" + (i + 1) + "个传入的code为空");
            if (maps.get(i).get("hangcode") == null)
                throw new RuntimeException("第" + (i + 1) + "个传入的hangcode为空");
            if (maps.get(i).get("surplus") == null)
                throw new RuntimeException("第" + (i + 1) + "个传入的surplus为空");
        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void handleCdKh(Map<String, Object> map) {
        Gd gd = gdDao.findGdByHangCode(map.get("hangcode").toString());
        if (gd != null && gd.getId() != null) {
            //Kh kh = gd.getKh();
            Kh kh = null;
            if (kh != null && kh.getId() != null) {
                Double surplus = Double.valueOf((String) map.get("surplus"));
                Double comjz = (Math.round((kh.getGdsl() / kh.getGdjs()) * 1000000) / 1000000.0);
                kh.setKkdsl(kh.getKkdsl() + surplus * (kh.getJz() == null ? comjz : kh.getJz()));
                kh.setGdjshj(kh.getGdjshj() - kh.getGdjs());
                kh.setGdslhj(kh.getGdslhj() - kh.getGdsl());
                kh.setGdjs(0);
                kh.setGdsl(0d);
                khDao.save(kh);
                gd.setDeleted(1);
                gdDao.save(gd);
            } else {
                this.changeKhWithOut(gd, map); //有些挂单单据 没有关联卡号（上线后的添加的卡号Id）
            }
            // gdDao.inserToCdRz(gd.getId(), kh.getId(), kh.getGdjs(), kh.getGdsl(), kh.getGdjshj(), kh.getGdslhj(), kh.getKkdsl(), Double.valueOf((String) map.get("surplus")), new Date());//记录撤单日志
        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public synchronized void changeKhWithOut(Gd gd, Map<String, Object> map) {
        String[] strings = gd.getResource_serial_number().split("-");
        Cgd cgd = cgdDao.findCgdFindCgdh(strings[0] + "-" + strings[1]);
        List<Kh> khList = cgd.getKhList();
        for (Kh kh : khList) {
            if (kh.getPxh() == Integer.parseInt(strings[2])) {
                if (kh.getGdsl() != null) {
                    Double surplus = Double.valueOf((String) map.get("surplus"));
                    Double comjz = (Math.round((kh.getGdsl() / kh.getGdjs()) * 1000000) / 1000000.0);
                    kh.setKkdsl(kh.getKkdsl() + surplus * (kh.getJz() == null ? comjz : kh.getJz()));
                    kh.setGdjshj(kh.getGdjshj() - kh.getGdjs());
                    kh.setGdslhj(kh.getGdslhj() - kh.getGdsl());
                    kh.setGdjs(0);
                    kh.setGdsl(0d);
                    khDao.save(kh);
                    gd.setDeleted(1);
                    gdDao.save(gd);
                }
            }
        }
    }


    public String createCdJsonToInterFace(List<Gd> gdList) {
        StringBuffer sb = new StringBuffer();
        sb.append("[");
        for (Gd gd : gdList) {
            sb.append("{\"resource_serial_number\":\"").append(gd.getResource_serial_number()).append("\",");
//            sb.append("\"hangcode\":\"").append(gd.getHangcode()).append("\"},");
        }
        sb = sb.deleteCharAt(sb.length() - 1);
        sb.append("]");
        return sb.toString();
    }


    @Autowired
    public void setGdDao(GdDao gdDao) {
        this.gdDao = gdDao;
    }

    @Autowired
    public void setWebserviceTransService(WebserviceTransService webserviceTransService) {
        this.webserviceTransService = webserviceTransService;
    }

    @Autowired
    public void setKhDao(KhDao khDao) {
        this.khDao = khDao;
    }

    @Autowired
    public void setCgdDao(CgdDao cgdDao) {
        this.cgdDao = cgdDao;
    }
}
